package com.cdd.agent.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.cdd.common.constant.Constants;
import com.cdd.common.constant.RedisKeys;
import com.cdd.common.core.controller.BaseController;
import com.cdd.common.core.domain.Result;
import com.cdd.common.core.domain.model.LoginUser;
import com.cdd.common.core.redis.RedisCache;
import com.cdd.common.core.redis.TokenRedisCache;
import com.cdd.common.utils.uuid.UUID;
import com.cdd.agent.api.domain.dto.AgentLoginDto;
import com.cdd.common.domain.entity.AgentUser;
import com.cdd.common.domain.entity.AppUser;
import com.cdd.agent.api.domain.vo.UserBaseDto;
import com.cdd.agent.api.service.AgentUserService;
import com.cdd.agent.api.service.AppGuildService;
import com.cdd.agent.api.service.AppUserService;
import com.cdd.agent.api.service.GuildUserCountService;
import com.cdd.framework.oauth2.enums.LoginType;
import com.cdd.framework.web.service.SysTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@CrossOrigin
@RestController
@RequestMapping("")
public class AgentGuildController extends BaseController {

    @Resource
    private AppUserService appUserService;
    @Resource
    private AgentUserService agentUserService;
    @Resource
    private AppGuildService appGuildService;
    @Resource
    private GuildUserCountService guildUserCountService;
    @Resource
    private TokenRedisCache tokenRedisCache;

    @PostMapping("/login")
    public Result login(@RequestBody AgentLoginDto loginDto) {
        if (loginDto.getLoginType() == null) {
            return this.errorJSON("请选择登录类型！");
        }
        if (StringUtils.isBlank(loginDto.getLoginname())) {
            return this.errorJSON("账号不能为空！");
        }
        if (StringUtils.isBlank(loginDto.getPassword())) {
            return this.errorJSON("密码不能为空！");
        }
        AppUser user;
        //loginType：1-代理，2-工会管理员
        if (loginDto.getLoginType() == 1) {
            AgentUser agentUser = agentUserService.findByUser(loginDto.getLoginname(), loginDto.getPassword());
            if (agentUser == null || agentUser.getUserId()  == null || agentUser.getUserId() <= 0) {
                return this.errorJSON("该用户不存在或密码错误！");
            }
            user = appUserService.get(agentUser.getUserId());
            if (user == null || user.getId() == null || user.getId() <= 0) {
                return this.errorJSON("该用户不存在或密码错误！");
            }
        } else if (loginDto.getLoginType() == 2) {
            user = appUserService.findByUser(loginDto.getLoginname(), loginDto.getPassword());
            if (user == null || user.getId() == null || user.getId() <= 0) {
                return this.errorJSON("该用户不存在或密码错误！");
            }
            if (appGuildService.get(user.getId()) == null) {
                return this.errorJSON("非工会管理员无法登录！");
            }
        } else {
            return this.errorJSON("请选择正确的登录类型！");
        }
        user.setLoginType(loginDto.getLoginType());
        //用户信息加入缓存
        String token = UUID.fastUUID().toString(true);
        JSONObject object = new JSONObject();
        object.put(Constants.client_toke, token);
        UserBaseDto ud = new UserBaseDto();
        BeanUtils.copyProperties(user, ud);
        object.put("user", ud);

        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setLoginTime(LocalDateTime.now());
        loginUser.setLoginType(LoginType.SYS.name());
        tokenRedisCache.setToken(token, loginUser, Constants.token_effective_time);
        return sucessJSON(object);
    }

    @GetMapping("/userInfo")
    public Result userInfo() {
        AppUser user = getAppUser();
        if (user == null){
            return errorJSON("请登录！");
        }
        return sucessJSON(BeanUtil.copyProperties(user, UserBaseDto.class));
    }

    /**
     * @desc 获取推广链接
     */
    @GetMapping("/get/tg/url")
    public Result getTgUrl() {
        return sucessJSON((Object) guildUserCountService.getTgUrl(getUserId()));
    }

    /**
     * @desc 账户信息
     */
    @GetMapping("/baseInfo")
    public Result baseInfo() {
        return sucessJSON(guildUserCountService.getGuildBaseInfo(getUserId()));
    }

}
